﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel
{
    public class EditValueWindowViewModel : ViewModelBase
    {
        #region PLC地址
        /// <summary>
        /// PLC地址
        /// <author>作者：徐一贺</author>  
        /// </summary
        private readonly string PlcAddress = PlcHelper.GetPlcAddress();
        #endregion PLC地址
        /// <summary>
        /// 当前的标签
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private TagInfo _TagInfo;
        /// <summary>
        /// 当前的标签
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public TagInfo TagInfo
        {
            get { return _TagInfo; }
            set
            {
                _TagInfo = value;
                RaisePropertyChanged("TagInfo");
            }
        }
        /// <summary>
        /// 使用显示值/修改值
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private string _TagValue;
        /// <summary>
        /// 使用显示值/修改值
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public string TagValue
        {
            get { return _TagValue; }
            set
            {
                _TagValue = value;
                RaisePropertyChanged("TagValue");
            }
        }
        /// <summary>
        /// 下拉列表
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private ObservableCollection<TagInfo> _ValueItems;
        /// <summary>
        /// 下拉列表
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public ObservableCollection<TagInfo> ValueItems
        {
            get { return _ValueItems; }
            set
            {
                _ValueItems = value;
                RaisePropertyChanged("ValueItems");
            }
        }

        /// <summary>
        /// 下拉列表选中项索引
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private int _ValueIndex;
        /// <summary>
        /// 下拉列表选中项索引
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public int ValueIndex
        {
            get { return _ValueIndex; }
            set
            {
                _ValueIndex = value;
                RaisePropertyChanged("ValueIndex");
            }
        }
        /// <summary>
        /// 是否显示文本框框
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private Visibility _ShowTextBoxVisibility;
        /// <summary>
        /// 是否显示文本框框
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public Visibility ShowTextBoxVisibility
        {
            get
            {
                return _ShowTextBoxVisibility;
            }
            set
            {
                _ShowTextBoxVisibility = value;
                RaisePropertyChanged("ShowTextBoxVisibility");
            }
        }
        /// <summary>
        /// 是否显示下拉框
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private Visibility _ShowComBoxVisibility;
        /// <summary>
        /// 是否显示下拉框
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public Visibility ShowComBoxVisibility
        {
            get
            {
                return _ShowComBoxVisibility;
            }
            set
            {
                _ShowComBoxVisibility = value;
                RaisePropertyChanged("ShowComBoxVisibility");
            }
        }

        /// <summary>
        /// 下拉框列表
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private ObservableCollection<TagInfo> _ComBoxItems = new ObservableCollection<TagInfo>();
        /// <summary>
        /// 下拉框列表
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public ObservableCollection<TagInfo> ComBoxItems
        {
            get
            {
                return _ComBoxItems;
            }
            set
            {
                _ComBoxItems = value;
                RaisePropertyChanged("ComBoxItems");
            }
        }

        /// <summary>
        /// 下拉框当前选中
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private int _ValueSelectIndex;
        /// <summary>
        /// 下拉框当前选中
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public int ValueSelectIndex
        {
            get
            {
                return _ValueSelectIndex;
            }
            set
            {
                _ValueSelectIndex = value;
                RaisePropertyChanged("ValueSelectIndex");
            }
        }
        /// <summary>
        /// 关闭取消命令
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public DelegateCommand CancelCommand { get; set; }
        /// <summary>
        /// 保存命令
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public DelegateCommand SaveCommand { get; set; }

        /// <summary>
        /// 构造方法
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public EditValueWindowViewModel()
        {
            ValueItems = new ObservableCollection<TagInfo>();
            TagInfo tagInfo = new TagInfo();
            tagInfo.Value = "False";
            ValueItems.Add(tagInfo);
            tagInfo = new TagInfo();
            tagInfo.Value = "True";
            ValueItems.Add(tagInfo);
            //使用委托初始化取消/关闭窗口命令
            CancelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(CancelHandler)
            };
            //使用委托初始化保存命令
            SaveCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SaveHandler)
            };
        }

        /// <summary>
        /// 保存处理程序
        /// <author>作者：徐一贺</author>  
        /// </summary>
        /// <param name="obj">参数</param>
        private void SaveHandler(object obj)
        {
            try
            {
                //西门子对象
                SiemensS7Net siemens = null;
                //连接对象
                OperateResult connect = null;
                OperateResult operateResult = null;
                // 西门子PLC通讯，指定PLC的ip地址和端口号
                siemens = new SiemensS7Net(SiemensPLCS.S1500, PlcAddress);
                // 连接对象
                connect = siemens.ConnectServer();
                if (!connect.IsSuccess)
                {
                    WindowManager.ShowWarning("警告", "与PLC连接中断，请检查网络通讯是否正常！");
                }
                else
                {
                    if (TagInfo.ValueType == "Bool")
                    {
                        if (ValueSelectIndex == 1)
                        {
                            TagInfo.Value = "True";
                        }
                        else if (ValueSelectIndex == 0)
                        {
                            TagInfo.Value = "False";
                        }
                        operateResult = siemens.Write(TagInfo.Address, bool.Parse(TagInfo.Value.ToLower()));
                    }
                    else if (TagInfo.ValueType == "DInt")
                    {
                        operateResult = siemens.Write(TagInfo.Address, Int32.Parse(TagValue));
                    }
                    while (true)
                    {
                        if (operateResult.IsSuccess)
                        {
                            WindowManager.ShowWarning("提示", "保存成功！");
                            TagInfo = new TagInfo();
                            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideEditValueWindow"));
                            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "ComTestReLoadTagList"));
                            break;
                        }
                        Thread.Sleep(100);
                    }
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "通讯测试编辑控制程序块值异常");
            }
        }


        /// <summary>
        /// 取消/关闭窗口命令处理程序
        /// <author>作者：徐一贺</author>  
        /// </summary>
        /// <param name="obj">参数</param>
        private void CancelHandler(object obj)
        {
            TagInfo = new TagInfo();
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideEditValueWindow"));
        }

        /// <summary>
        /// 加载标签数据
        /// <author>作者：徐一贺</author>  
        /// </summary>
        /// <param name="IncomingTagInfo">要修改值的标签</param>
        public void LoadTagInfo(TagInfo IncomingTagInfo)
        {
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                TagInfo = TransExpV2<TagInfo, TagInfo>.Trans(IncomingTagInfo);
                TagInfo = IncomingTagInfo;
                if (TagInfo.ValueType == "Bool")
                {
                    ShowComBoxVisibility = Visibility.Visible;
                    if (TagInfo.Value == "True")
                    {
                        ValueSelectIndex = 0;
                    }
                    else
                    {
                        ValueSelectIndex = 1;
                    }
                }
                else
                {
                    ShowComBoxVisibility = Visibility.Hidden;
                }
                if (TagInfo.ValueType == "DInt")
                {
                    ShowTextBoxVisibility = Visibility.Visible;
                    TagValue = TagInfo.Value;
                }
                else
                {
                    ShowTextBoxVisibility = Visibility.Hidden;
                }
            });
        }
    }
}
